<template>
   <div class="app-container">
      <el-row :gutter="20">
         <!--阶段数据-->
         <el-col :span="4" :xs="24">
            <div class="head-container">
               <el-input
                  v-model="deptName"
                  placeholder="请输入阶段名称"
                  clearable
                  prefix-icon="Search"
                  style="margin-bottom: 20px"
               />
            </div>
            <div class="head-container">
               <el-tree
                  expand-on-click-node="true"
                   accordion="true"
                  :data="deptOptions"
                  :props="{ label: 'name', children: 'children',value:'id'}"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="deptTreeRef"
                  node-key="id"
                  lazy
                  :load="load"
                  highlight-current
                  @node-click="handleNodeClick"
               />
            </div>
         </el-col>
         <!--用户数据-->
         <el-col :span="20" :xs="24">
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

               <el-form-item label="用户名称" style="font-weight: 800;" prop="nickname">
                 <span></span>
                  <el-input
                     v-model="queryParams.nickname"
                     placeholder="请输入用户名称"
                     clearable
                     style="width: 240px"
                  />
               </el-form-item>
               <el-form-item label="手机号码" style="font-weight: 800;" prop="phone">
                  <el-input
                     v-model="queryParams.phone"
                     placeholder="请输入手机号码"
                     clearable
                     style="width: 240px"
                  />
               </el-form-item>
               <el-form-item label="状态" style="font-weight: 800;" prop="state">
                  <el-select
                     v-model="queryParams.state"
                     placeholder="学生状态"
                     clearable
                     style="width: 240px; font-weight: 600;"
                  >
                     <el-option
                        v-for="dict in student_array_state"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                     />
                  </el-select>
               </el-form-item>
               <el-form-item label="创建时间" style="width: 308px; font-weight: 800;">
                  <el-date-picker
                     v-model="queryParams.createTime"
                     value-format="YYYY-MM-DD"
                     type="daterange"
                     range-separator="-"
                     start-placeholder="开始日期"
                     end-placeholder="结束日期"
                  ></el-date-picker>
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="getList" style="width: 73px; height: 28px; font-size: 10px;">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery(queryRef)" style="width: 73px; height: 28px; font-size: 10px;">重置</el-button>
               </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="primary"
                     plain
                     icon="Plus"
                     @click="handleAdd"
                     v-hasPermi="['system:user:add']"
                  >新增</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="success"
                     plain
                     icon="Edit"
                     :disabled="single"
                     @click="handleUpdate"
                     v-hasPermi="['system:user:edit']"
                  >修改</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="danger"
                     plain
                     icon="Delete"
                     :disabled="multiple"
                     @click="handleDelete"
                     v-hasPermi="['system:user:remove']"
                  >删除</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="info"
                     plain
                     icon="Upload"
                     @click="handleImport"
                     v-hasPermi="['system:user:import']"
                  >导入</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="warning"
                     plain
                     icon="Download"
                     @click="handleExport"
                     v-hasPermi="['system:user:export']"
                  >导出</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     style="width: 200px; height: 28px; font-size: 10px;"
                     type="danger"
                     plain
                     @click="clearAllStart"
                     v-hasPermi="['system:user:export']"
                  >清空全部用户登录状态( 请勿重复点击 )</el-button>
               </el-col>
               <el-col :span="1.5" style="margin-left: 91%;">
              <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top"
                v-if="search">
                <el-button circle icon="Search" @click="toggleSearch()" />
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="刷新" placement="top">
              <el-button circle icon="Refresh" @click="refresh()" />
              </el-tooltip>
             </el-col>
            </el-row>
             <!-- 列表查询 -->
            <el-table v-loading="loading" :data="userList"  @selection-change="handleSelectionChange" :header-cell-style="{ background: '#eee', color: '#909399' }">
               <template #empty v-if="userList.length == 0">
                <el-empty description="暂时还没有学生信息哦~" />
              </template>
               <el-table-column type="selection" width="50" align="center" />
               <el-table-column label="头像" align="center">
                  <template #default="scope">
                   <el-avatar :size="50" :src="scope.row.avatar"/>
                  </template>
               </el-table-column>
               <el-table-column label="编号" align="center" key="userId" prop="userId" />
               <el-table-column label="账号" align="center" key="username" prop="username" :show-overflow-tooltip="true" />
               <el-table-column label="学号" align="center" key="studentId" prop="studentId" :show-overflow-tooltip="true" />
               <el-table-column label="姓名" align="center" key="nickname" prop="nickname" :show-overflow-tooltip="true" />
               <el-table-column label="邮箱" align="center" key="email" prop="email" :show-overflow-tooltip="true" />
               <el-table-column label="手机号" align="center" key="phone" prop="phone" :show-overflow-tooltip="true"/>
               <el-table-column label="状态" align="center" key="state">
                  <template #default="scope">
                     <el-switch
                        v-model="scope.row.state"
                        :active-value="0"
                        :inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                     ></el-switch>
                  </template>
               </el-table-column>
               <el-table-column label="班级" align="center" key="className" prop="className" :show-overflow-tooltip="true" />
               <el-table-column label="阶段" align="center" key="levelName" prop="levelName" :show-overflow-tooltip="true" />
               <el-table-column label="市场部" align="center" key="name" prop="name" :show-overflow-tooltip="true" />
               <el-table-column label="创建时间" align="center" prop="createTime" width="100" :show-overflow-tooltip="true">
                  <template #default="scope">
                     <span>{{ scope.row.createTime}}</span>
                  </template>
               </el-table-column>

               <el-table-column label="操作" align="center" width="110" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']"></el-button>
                     </el-tooltip>
                     <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']"></el-button>
                     </el-tooltip>
                     <el-tooltip content="重置密码" placement="top" v-if="scope.row.userId !== 1">
                         <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']"></el-button>
                     </el-tooltip>
                  </template>
               </el-table-column>
            </el-table>
         </el-col>
      </el-row>
   </div>
    <!-- 分页 -->
     <el-pagination
     style="margin-left: 18%;"       
     v-model:current-page="currentPage4"
     v-model:page-size="pageSize4"
     :page-sizes="[5, 10, 15, 20]"
     layout="total, sizes, prev, pager, next, jumper"
     :total="total"
     @size-change="handleSizeChange"
     @current-change="handleCurrentChange"
     background
   />
   <!-- 新增弹框 -->
   <el-dialog
   style="border-radius: var(--el-border-radius-base);"
   v-model="centerDialogVisible"
   :title="titles"
   width="500"
   align-center>

   <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm">
        
   <el-form-item label="账号" style="font-weight: 800;" prop="username">
     <el-input v-model="ruleForm.username" placeholder="输入要添加的账号"/>
   </el-form-item>
   <el-form-item label="用户名" style="font-weight: 800;" prop="nickname">
     <el-input v-model="ruleForm.nickname" placeholder="输入要添加的用户名"/>
   </el-form-item>
   <el-form-item label="所选班级" style="font-weight: 800;" prop="classId">
     <!-- <el-input v-model="ruleForm.classId" /> -->
      <el-tree-select
         placeholder="请选择要添加的班级"
         accordion="true"
         v-model="ruleForm.classId"
         :props="{ label: 'name', children: 'children',value:'classId'}"
         :data="cacheData"
         style="width: 240px; font-weight: 400;"
         />
   </el-form-item>
   <el-form-item label="手机号" style="font-weight: 800;" prop="phone">
     <el-input v-model="ruleForm.phone" placeholder="输入要添加的手机号"/>
   </el-form-item>
   <el-form-item label="市场部" style="font-weight: 800;" prop="mdId">
     <!-- <el-input v-model="ruleForm.mdId" /> -->
     <el-select v-model="ruleForm.mdId" placeholder="选择市场部" style="width: 240px;font-weight: 400;">
   <el-option
     v-for="item in mdcities"
     :key="item.id"
     :label="item.name"
     :value="item.id">
   </el-option>
 </el-select>
   </el-form-item>
   <el-form-item label="性别" style="font-weight: 800;" prop="sex">
     <!-- <el-input v-model="ruleForm.sex" /> -->
     <el-radio :value="0" v-model="ruleForm.sex">男</el-radio>
     <el-radio :value="1" v-model="ruleForm.sex">女</el-radio>
   </el-form-item>
   <el-form-item label="邮箱" style="font-weight: 800;" prop="email">
     <el-input v-model="ruleForm.email" placeholder="输入要添加的邮箱"/>
   </el-form-item>

   <el-form-item>
     <el-button type="primary" @click="submitForm_student(ruleFormRef)">
       确认
     </el-button>
     &nbsp;&nbsp;&nbsp;
     <span v-if="titles =='新增学生'">
     <el-button @click="resetForm_student(ruleFormRef)">重置</el-button>
    </span>
    <span v-else>
      <el-button @click="centerDialogVisible = false">取消</el-button>
    </span>
   </el-form-item>
 </el-form>

 </el-dialog>
 <!-- 导入弹框 -->
      <!-- 新增弹框 -->
      <el-dialog
   style="border-radius: var(--el-border-radius-base);"
   v-model="centerDialogVisible_file"
   title="导入学生数据"
   width="500"
   align-center>

   <el-upload
   v-loading="loading"
   class="upload-demo"
   drag
   action=""
   :http-request="uploadFile"
   multiple
 >
   <el-icon class="el-icon--upload"><upload-filled/></el-icon>
   <div class="el-upload__text">
     Drop file here or <em>click to upload</em>
   </div>
   <template #tip>
     <div class="el-upload__tip">
       jpg/png files with a size less than 500kb
     </div>
   </template>
 </el-upload>
 <el-button @click="file_submit">确认</el-button> <el-button @click="centerDialogVisible_file = false">取消</el-button>
  </el-dialog>
</template>

<script setup name="User">
import { clearStart } from "@/api/user/login"
import { getTokeName } from "@/utils/comstants";
import { reactive, ref, toRefs,watch } from "vue";
import { studentLimit,addStudent,allClass,allMarket,updateStudent,delBatchStudent,disable,resetPassword,upload,download,stu_list_tree} from "@/api/admin/student/student_api.js"
import { ElMessage,ElMessageBox,ElTree } from "element-plus";
const queryRef=ref()
const ruleFormRef = ref()
const showSearch = ref(true); //动态隐藏
const student_array_state=ref([{value:0,label:"正常"},{value:1,label:"禁用"}]) //学生状态数组
const userList = ref([]);//用户列表
const loading =ref(true)//页面加载
const currentPage4 = ref(1)
const pageSize4 = ref(5)
const total=ref(5)
const deptName=ref()//阶段名称查询
const deptTreeRef=ref()//3级菜单
const titles=ref('')
const centerDialogVisible = ref(false);//新增修改弹框
const centerDialogVisible_file = ref(false) //导入文件弹框
const mdcities = ref([])//市场部数组
const classcities = ref([])//班级数组
const deptOptions=ref([]) //三级菜单
const cacheData = ref([])  //懒加载
stu_list_tree().then(res=>{
  //res.data.obj[0].children  相当于 
  cacheData.value=res.data.obj[0].children
})
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
 if (!value) return true
 return data.name.includes(value);
}

const clearAllStart=()=>{
   clearStart().then(res=>{
      ElMessage.success("清空成功( 请勿重复点击 )")
   })
}

watch(deptName, (val) => {
 deptTreeRef.value.filter(val)
})
//属性查询方法
function treefunlist(){
 stu_list_tree().then(res=>{
   deptOptions.value=res.data.obj
 })
}
//3级菜单懒加载
const load = (node, resolve) => {
  //给查询图书列表赋值参数
  if( node.data.id != 2 && node.data.id != 3 && node.data.id != 4 && node.data.id != 1 ){return resolve([])}
//   if (node.isLeaf) return resolve([])
 setTimeout(() => {
  if(node.data.id == 1){
     resolve(node.data.children)
  }else if(node.data.id == 2){//实训阶段
     resolve(node.data.children)
  }else if(node.data.id == 3){//专高阶段     
     resolve(node.data.children)//专高阶段数据
  }else if(node.data.id == 4){ //专业阶段     
     resolve(node.data.children)
  }else{//其他情况
    resolve([])
  }   
 }, 400)
}

const datanum = []  
const user_student_info = ref()
//多选
const handleSelectionChange = (val) => {
   datanum.splice(0,datanum.length);
   val.forEach(element => {
       datanum.push(element.userId)
   });
   //说明用户选择1条数据
   if(datanum.length == 1){
     user_student_info.value=val
   }
}

const queryParams = ref({
   pageNum:currentPage4.value,
   pageSize:pageSize4.value,
   nickname:'',
   phone:'',
   mdId:'',
   createTime:[],
   classId:''
})
//查询列表
function getList(){
  loading.value = true
  studentLimit(queryParams.value).then(res=>{
     loading.value = false
     userList.value=res.data.obj.list
     total.value=res.data.obj.total
     userList.value.forEach(element => {
        //创建时间格式化
     if(element.updateTime !=null){
      element.createTime=caseTime(element.createTime)
     }
     });
  })
}
//添加或修改数据
const ruleForm = ref({
  username: '',
  nickname: '',
  classId: '',
  mdId:'',
  phone: '',
  sex: '',
  email: '',
  avatar:'',
})

const rules = reactive({
  username: [{ required: true, message: '账号不能为空', trigger: 'blur' },{ min: 3, max: 11, message: '账号长度为3~8位之间', trigger: 'blur' }],
  nickname: [{ required: true, message: '姓名不能为空', trigger: 'blur' },{pattern:/^[\u4e00-\u9fa5]+$/,message: '姓名必须是中文', trigger: 'blur'},{ min: 2, max: 8, message: '姓名长度必须大于或等于2位', trigger: 'blur' }],
  classId: [{ required: true, message: '班级不能为空', trigger: 'blur' },],
  mdId: [{ required: true, message: '市场部不能为空', trigger: 'blur' },],
  phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' },{pattern:/^[1][3-9]\d{9}$/,message: '手机号格式不正确', trigger: 'blur'}],
  sex: [{ required: true, message: '性别不能为空', trigger: 'blur' },],
  email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' },{pattern:/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,4})+$/,message: '邮箱格式不正确', trigger: 'blur'}],
})

//搜索重置
const resetQuery = (formEl) => {
 if (!formEl) return
 formEl.resetFields() 
 queryParams.value.classId='' //让班级id为空
 queryParams.value.createTime=[]
 getList()
}

//新增初始化方法
function handleAdd(){
  ruleForm.value={}//清空
  centerDialogVisible.value=true
  titles.value='新增学生';
  ruleForm.value.avatar="https://img1.baidu.com/it/u=1654815901,4067385000&fm=253&fmt=auto&app=120&f=JPEG?w=533&h=500"
}
//修改初始化方法
function handleUpdate(row){
  ruleForm.value={}//清空
  if(datanum.length == 1){
      centerDialogVisible.value=true
     titles.value='修改学生';
     ruleForm.value=user_student_info.value[0]
  }else if(row.userId != null){
     row.password=""
     row.updateTime=""
     row.createTime=""
     centerDialogVisible.value=true
     titles.value='修改学生';
     ruleForm.value=row
  }else{
     ElMessage.warning("请选择一个学生哦")
  }
}

//添加方法
function submitForm_student(formEl){
  if (!formEl) return
 formEl.validate((valid) => {
   if (valid) {
if(ruleForm.value.userId != null){//修改
   updateStudent(ruleForm.value).then(res=>{
        if(res.data.code == 200){
           centerDialogVisible.value=false
            ElMessage.success('修改学生成功');
            getList();
        }else{
           ElMessage.error(res.data.message)
        }
     })
  }else{//添加
  addStudent(ruleForm.value).then(res=>{
        if(res.data.code == 200){
           centerDialogVisible.value=false
            ElMessage.success('新增学生成功');
            getList();
        }else{
           ElMessage.error(res.data.message)
        }
     })
}
   } 
 })
}

//删除方法
function handleDelete(row){
  ElMessageBox.confirm(
   '您确认要删除嘛?',
   '温馨提示',
   {
     confirmButtonText: '确认',
     cancelButtonText: '取消',
     type: 'warning',
   }
 )
   .then(() => {
    if(datanum.length>0){    //删除方法
     delBatchStudent(datanum).then(res=>{
        if(res.data.code == 200){
           ElMessage.success("删除成功");
           getList();
        }else{
          ElMessage.error("删除失败");
        }
     })
    }else if(row.userId!= null){
     delBatchStudent(row.userId).then(res=>{
        if(res.data.code == 200){
           ElMessage.success("删除成功");
           getList();
        }else{
          ElMessage.error("删除失败");
        }
     })
    }else{
     ElMessage.warning("请至少选择一个")
    }
    
   })
   .catch(() => {
     ElMessage({
       type: 'info',
       message: '已取消删除',
     })
   })
}

//导入方法
function handleImport(){
  centerDialogVisible_file.value=true
};

const form=ref({
   file:''
})
//覆盖自定义上传的默认行为
function uploadFile(val){
    form.value.file=''//清空
   form.value.file=val.file
}
//确认提交文件
function file_submit(){
   loading.value=true
  upload(form.value).then(res=>{
     loading.value=false
     if(res.data.code == 200){
        ElMessage.success("导入成功");
        form.value.file=''//清空
        centerDialogVisible_file.value=false
        getList();
     }else{
        ElMessage.error("导入失败");
        centerDialogVisible_file.value=false
     }
  })
}

//导出方法
function handleExport(){
    download().then(res=>{
     const xlsx = "application/vnd.ms-excel";
     let blob = new Blob([res.data],{type:xlsx})
       const enlink = document.createElement('a')
       enlink.download='学生模板.xlsx';
       enlink.style.display='none',
       enlink.href = URL.createObjectURL(blob)
       document.body.appendChild(enlink);
       enlink.click();
       URL.revokeObjectURL(enlink.href);
       document.body.removeChild(enlink)
    })
}
const user_student_status=ref({
  userId:'',
  status:'',
})
//用户状态修改
function handleStatusChange(row) {
    user_student_status.value.userId=row.userId
    user_student_status.value.status=row.state
    ElMessageBox.confirm(
   '您确认要修改状态嘛?',
   '温馨提示',
   {
     confirmButtonText: '确认',
     cancelButtonText: '取消',
     type: 'warning',
   }
 )
   .then(() => {
     disable(user_student_status.value).then(res=>{
        if(res.data.code == 200){
           ElMessage.success("状态修改成功");
           getList();
        }else{
          ElMessage.error("状态修改失败");
        }
     })
   })
   .catch(() => {
     ElMessage({
       type: 'info',
       message: '已取消',
     })
     getList()
   })
}

//重置密码
function handleResetPwd(row){
  resetPassword(row.userId).then(res=>{
     if(res.data.code == 200){
         ElMessage.success("重置成功")
     }else{
        ElMessage.error("重置失败")
     }
   })
}

//控制条数
const handleSizeChange = (val) => {
   queryParams.value.pageSize=val
   getList()
}
//控制页数
const handleCurrentChange = (val) => {
   queryParams.value.pageNum=val
   getList()
}

//阶段名称根据班级查询学生方法
function handleNodeClick(data){
  if(data.id != 1 && data.id != 2 && data.id != 3 && data.id != 4){
     queryParams.value.classId=data.classId
      getList();
  }
}
//重置添加或者修改
const resetForm_student = (formEl) => {
   // ==================================================================
 ruleForm.value={}
 if (!formEl) return
 formEl.resetFields()
}

/**时间转换 */
function caseTime(date){
   let time=new Date(date);
   let year=time.getFullYear();
   let month=time.getMonth()+1;
   let day=time.getDate()+1;
   let hours=time.getHours();
   let minutes=time.getMinutes();
   if(month<=9){
       month='0'+month
   }

   if(day<=9){
      day='0'+day
   }

   if(hours<=9){
     hours='0'+hours
   }
   if(minutes<=9){
     minutes='0'+minutes
   }
   return year+"-"+month+"-"+day+" "+hours+":"+minutes;
}
//班级查询所有
function class_list(){
  allClass().then(res=>{
     classcities.value=res.data.obj
  })
}
//市场部查询所有
function Marketing_list(){
  allMarket().then(res=>{
     mdcities.value=res.data.obj
  })
}

const props = defineProps({
  /* 是否显示检索条件 */
  showSearch: {
     type: Boolean,
     default: true,
  },
  /* 显隐列信息 */
  columns: {
     type: Array,
  },
  /* 是否显示检索图标 */
  search: {
     type: Boolean,
     default: true,
  },
  /* 显隐列类型（transfer穿梭框、checkbox复选框） */
  showColumnsType: {
     type: String,
     default: "checkbox",
  },
  /* 右外边距 */
  gutter: {
     type: Number,
     default: 10,
  },
})

const emits = defineEmits(['update:showSearch', 'queryTable']);

// 搜索
function toggleSearch() {
 if (showSearch.value == true) {
    showSearch.value = false
 } else {
    showSearch.value = true
 }
 emits("update:showSearch", !props.showSearch);
}

// 刷新
function refresh() {
 getList()
}

getList()
class_list()
Marketing_list()
treefunlist()//树形查询
</script>
<style>
.button_clss{
  width: 73px;
  height: 28px;
}
</style>
